package edu.yuhf.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;

import edu.yuhf.domain.Hobby;
import edu.yuhf.domain.NativePlace;
import edu.yuhf.domain.Page;
import edu.yuhf.domain.User;
import edu.yuhf.domain.UserDetail;
import edu.yuhf.service.HobbyServiceImpl;
import edu.yuhf.service.NativePlaceServiceImpl;
import edu.yuhf.service.UserRoleServiceImpl;
import edu.yuhf.service.UserServiceImpl;
import edu.yuhf.service.iface.HobbyService;
import edu.yuhf.service.iface.NativePlaceService;
import edu.yuhf.service.iface.UserRoleService;
import edu.yuhf.service.iface.UserService;

@WebServlet("/user.servlet")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static Logger log=Logger.getLogger(UserServlet.class);

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		UserService userService=new UserServiceImpl();
		HobbyService hobbyService=new HobbyServiceImpl(); 
		NativePlaceService nativePlaceService=new NativePlaceServiceImpl();
		UserRoleService userRoleService=new UserRoleServiceImpl();
		
		String param=request.getParameter("param");
		String id=null==request.getParameter("id")?"":request.getParameter("id");
		String userId=null==request.getParameter("userId")?"":request.getParameter("userId");
		String userName=request.getParameter("userName");
		String password=request.getParameter("password");
		String nickName=request.getParameter("nickName");
		String rePassword=request.getParameter("rePassword");
		String sex=request.getParameter("sex");
		String phone=request.getParameter("phone");
		String email=request.getParameter("email");
		String birthday=request.getParameter("birthday");
		String hobbies=String.join(",",null==request.getParameterValues("hobbies")?new String[0]:request.getParameterValues("hobbies"));
		String city=request.getParameter("city");
		String isCookie=null==request.getParameter("isCookie")?"off":request.getParameter("isCookie");
		String ids=null==request.getParameter("ids")?"":request.getParameter("ids");
		
		String[] roleIds=request.getParameterValues("roleId");
		
		String keyword=null==request.getParameter("keyword")?"":request.getParameter("keyword");
		String currentPage=null==request.getParameter("currentPage")?"1":request.getParameter("currentPage");
		
		PrintWriter out=response.getWriter();
		String jsonString="";
		Map<String,Object> map=new HashMap<>();
		
		if("roleUpdate".equals(param)) {
			if(userRoleService.setUserRole(Integer.valueOf(userId), roleIds)) {
				out.print("<script>alert('修改用户角色操作成功！');window.location.href='user.servlet?param=init'</script>");
			}else {
				out.print("<script>alert('修改用户角色操作失败！');window.location.href='user.servlet?param=init'</script>");
			}
		}
		if("doUpdate".equals(param)) {
			User user=new User(Integer.valueOf(userId),userName,nickName,password,sex,email,phone);
			UserDetail userDetail=new UserDetail(0,city,hobbies,Integer.valueOf(userId),LocalDate.parse(birthday));
			log.debug(userDetail.getBirthday()+","+userDetail.getHobby_code()+","+userDetail.getNativePalce_code()+","+userDetail.getUserId());
			if(userService.updateUserAndUserDetail(user, userDetail)) {
				out.print("<script>alert('更新成功！');location.href='user.servlet?param=init'</script>");
			}else {
				out.print("<script>alert('更新失败！');location.href='user.servlet?param=init'</script>");
			}
		}
		if("update".equals(param)) {
			Optional<Map<String,Object>> optional=userService.queryUserAndUserDetailById(Integer.valueOf(id));
			List<Hobby> hobbiesVo=hobbyService.showHobbies();
			//获取已选择的爱好
			for(Hobby hobby:hobbiesVo)
				optional.ifPresent((uaud) -> {
					String temp = (String) uaud.get("hobby_code");
					if (null != temp && temp.indexOf(String.valueOf(hobby.getCode())) != -1) {
						hobby.setChecked(true);
					}
				});
			List<NativePlace> provinces=nativePlaceService.getProvince();
			List<NativePlace> cities=nativePlaceService.getCities();
			optional.ifPresent((uaud)->{
				map.put("result", "ok");
				map.put("userAndUserDetail",uaud);
				map.put("hobbies",hobbiesVo);
				map.put("provinces",provinces);
				map.put("cities",cities);
			});
			//map.put("result", "error");			
		}
		if("delete".equals(param)) {
			if(userService.deleteUser(ids)) {
				out.print("<script>alert('删除成功！');location.href='user.servlet?param=init'</script>");
			}else {
				out.print("<script>alert('删除失败！');location.href='user.servlet?param=init'</script>");
			}
		}
		if("init".equals(param)) {
			Page<List<Map<String,Object>>> page=new Page<>(Integer.valueOf(currentPage));
			page.setKeyword(keyword);

			userService.queryAllUserAndUserDetail(page);
			request.setAttribute("page",page);
			request.getRequestDispatcher("views/userManager.jsp").forward(request, response);
			
		}
		if("reg".equals(param)) {
			if(!password.equals(rePassword)) {
				out.print("<script>alert('两次输入的密码不一致！');location.href='register.jsp'</script>");
			}
			User user=new User(userName,nickName,password,sex,email,phone);
			UserDetail userDetail=new UserDetail(0,city,hobbies,0,LocalDate.parse(birthday));
			if(userService.insertUserInfo(user, userDetail)) {
				out.print("<script>alert('注册成功，请用注册信息登录！');location.href='login.jsp'</script>");
			}else {
				out.print("<script>alert('注册失败，系统故障和系统忙！');location.href='login.jsp'</script>");
			}
		}
		if("login".equals(param)) {
			User user=userService.checkUserNameAndPassword(userName, password);
			if(null!=user) {
				if("on".equals(isCookie)) {
					Cookie cookie=new Cookie("loginCookie", userName);
					cookie.setMaxAge(60*60*24*7);
					response.addCookie(cookie);
				}
				HttpSession session=request.getSession();
				session.setAttribute("user",user);
				session.setAttribute("name", user.getUserName());
				request.getRequestDispatcher("views/main.jsp").forward(request, response);
			}else {
				request.setAttribute("message", "用户名或密码错误！");
				request.getRequestDispatcher("login.jsp").forward(request, response);
			}
		}
		if("ghn".equals(param)) {
			List<Hobby> list=hobbyService.showHobbies();
			if(null!=list&&list.size()!=0) {
				map.put("result", "ok");
				map.put("list", list);
			}else {
				map.put("result", "no data");
			}
		}
		if("cud".equals(param)) {
			if(userService.checkUserName(userName)) {
				map.put("result","ok");
				map.put("message","用户名可以使用！");
			}else {
				map.put("result","error");
				map.put("message","用户名重复！");				
			}
		}
		jsonString=JSON.toJSONString(map);
		out.print(jsonString);
		out.flush();
		out.close();
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
